﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace SingleBlog.Web.Areas.Install.Controllers
{
    using Core.Data;
    using Models;
    using SingleBlog.Core.Services;
    using System.IO;
    using Newtonsoft.Json;
    using Microsoft.AspNetCore.Identity;
    using SingleBlog.UI.Filters;

    /// <summary>
    /// 表示安装的控制器。
    /// </summary>
    /// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" />
    [Area("install")]
    [AllowAnonymous,NoInstallationCheck]
    public class InstallController : Controller
    {
        private readonly SingleBlogDbContext _context;
        private readonly IDataInitializer _dataInitializer;
        private readonly SettingService _settingService;
        private readonly SignInManager<SingleBlogUser> _signInManager;
        public InstallController(
            SettingService settingService,
            SingleBlogDbContext context,
            IDataInitializer dataInitializer,
            SignInManager<SingleBlogUser> signInManager
            )
        {
            _context = context;
            _dataInitializer = dataInitializer;
            _settingService = settingService;
            _signInManager = signInManager;
        }

        public IActionResult Index()
        {
           return View();
        }

        /// <summary>
        /// 数据库检测
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Install()
        {
            ViewData["DbFile"] = System.IO.File.Exists($"{Directory.GetCurrentDirectory()}/SingleBlog.db.lock");

            ViewData["DbExist"] = _context.DatabaseExist();
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Install([FromForm]DbInitViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "表单验证有错误");
                return View(model);
            }
            try
            {
                try
                {
                    if (User.Identity.IsAuthenticated)
                    {
                        await _signInManager.SignOutAsync();
                    }

                    await _dataInitializer.InitializeAsync(model);
                }
                catch (DataInitializeException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    return View(model);
                }

                using (var fs = new FileStream($"{Directory.GetCurrentDirectory()}/SingleBlog.db.lock", FileMode.CreateNew, FileAccess.Write))
                {
                    var value = JsonConvert.SerializeObject(_settingService.GetSystemSetting()).MD5().ToBytes();
                    fs.Write(value, 0, value.Length);
                }
                
                return RedirectToAction("Success");
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", "程序安装出现错误，{0}".StringFormat(ex.Message));
            }
            return View(model);
        }

        public IActionResult Success()
        {
            return View();
        }
    }
}